package com.base.cn.platform.os.controller.manage.role;

import com.base.cn.platform.os.common.AdminBaseController;
import com.base.cn.platform.os.common.log.aop.AdminModuleEnum;
import com.base.cn.platform.os.common.log.aop.OpLog;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.common.utils.web.LoginUtil;
import com.base.cn.platform.os.service.manage.function.SysFunctionService;
import com.base.cn.platform.os.service.manage.join.RoleFunctionService;
import com.base.cn.platform.os.service.manage.join.RoleSubjectService;
import com.base.cn.platform.os.service.manage.join.UserRoleService;
import com.base.cn.platform.os.service.manage.role.SysRoleService;
import com.base.cn.platform.os.service.manage.subject.SubjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 角色管理员
 *
 * @author s.li
 * @create 2018-03-19 11:43
 */
@Controller
@RequestMapping("/admin/manage/role")
public class AdminRoleController  extends AdminBaseController {

    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SubjectService subjectService;
    @Autowired
    private SysFunctionService sysFunctionService;
    @Autowired
    private RoleSubjectService roleSubjectService;
    @Autowired
    private RoleFunctionService roleFunctionService;
    @Autowired
    private LoginUtil loginUtil;
    @Autowired
    private UserRoleService userRoleService;

    /**
     * 查看角色详情
     * @param id 角色ID
     * @return 操作页面
     */
    @RequestMapping("/roleInfo")
    public String roleInfo(Model model ,
                           @RequestParam("id") BigDecimal id){
        Map<String,Object> sysRole = sysRoleService.findSysRoleById(id,false,true);
        model.addAttribute("sysRole",sysRole);
        return resultPage("/manage/role/role-info");
    }

    /**
     * 角色管理列表
     * @return
     */
    @RequestMapping("/listSysRole")
    public String listSysRole(Model model){
        model.addAttribute("count",sysRoleService.count());
        return resultPage("/manage/role/role-list");
    }

    /**
     * 获取列表数据
     * @param model
     * @param currentPage 页码
     * @param params 查询条件
     * @return 数据页面
     */
    @RequestMapping("/ajax/ajaxListSysRole")
    public String ajaxListSysRole(Model model,
                                  @RequestParam(value = "currentPage",defaultValue = "1",required = false) int currentPage,
                                  @RequestBody Map<String,Object> params){
        Map<String,Object> dataMap = sysRoleService.findSysRoleList(params,currentPage);
        model.addAttribute("dataMap",dataMap);
        return resultPage("/manage/role/ajax-role-list");
    }

    /**
     * 初始化修改/添加页面
     * @param roleId 要修改的角色ID
     * @return 操作页面
     */
    @RequestMapping(value = {"/initAddRole","/initUpdateRole"})
    public String initAddRole(Model model,
                              @RequestParam(value = "roleId",required = false,defaultValue = "0") BigDecimal roleId,
                              @RequestParam(value = "type",required = false,defaultValue = "0") int type){
        Map<String,Object> sysRole = null;
        if(roleId.compareTo(new BigDecimal(0)) > 0){//修改
            sysRole = sysRoleService.findSysRoleById(roleId,false,false);
        }
        if(sysRole==null){
            sysRole = new HashMap<>();
        }
        model.addAttribute("type",type);
        model.addAttribute("sysRole",sysRole);
        return resultPage("/manage/role/save-role");
    }

    /**
     * 保存角色数据信息
     * @param sysRole 角色数据
     * @return Map<String,Object>
     */
    @RequestMapping("/saveSysRole")
    @ResponseBody
    @OpLog(module = AdminModuleEnum.SYS_USER,action = "创建或者修改角色")
    public Map<String,Object> saveSysRole(HttpServletRequest request,@RequestBody Map<String, Object> sysRole){
        BigDecimal sysUserId = loginUtil.getLoginUserId(request);
        sysRole.put("createUserId",sysUserId);
        return sysRoleService.updateOrAddRole(sysRole);
    }

    /**
     * 删除角色
     * @param ids 角色ID串，多个ID以“,”隔开
     * @return Map<String,Object>
     */
    @RequestMapping("/deleteSysRoleByIds")
    @ResponseBody
    public Map<String,Object> deleteSysRoleByIds(String ids){
        return sysRoleService.deleteSysRoleByIds(ids);
    }

    /**
     * 修改角色状态
     * @param roleIds 角色ID串
     * @param status 状态，1正常，2禁用
     * @return Map<String,Object>
     */
    @RequestMapping("/updateSysRoleStatus")
    @ResponseBody
    public Map<String,Object> updateSysRoleStatus(String roleIds ,int status){
        return sysRoleService.updateRoleStatus(roleIds,status);
    }

    /**
     * 初始化角色授权页面
     * @param roleId 角色ID
     * @return 操作页面
     */
    @RequestMapping("/initRoleFunction")
    public String initRoleFunction(Model model,
                                   HttpServletRequest request,
                                   @RequestParam("roleId") BigDecimal roleId,@RequestParam(value = "type",required = false,defaultValue = "0") int type){
        model.addAttribute("roleId",roleId);
        List<Map<String,Object>> functionLayeredList;
        if(roleId.compareTo(new BigDecimal(1))==0){//如果是超级管理角色，则获取所有状态正常的专业
            //获取所有的权限
            functionLayeredList = sysFunctionService.findAllFunctionList();
        }else{//如果是普通角色则只获取角色下对应的专业列表
            functionLayeredList = sysFunctionService.findLayeredUserFunctionList(loginUtil.getLoginUserId(request));
        }
        functionLayeredList = this.handleFunctionHasStatus(roleId,functionLayeredList);
        model.addAttribute("type",type);
        model.addAttribute("functionLayeredList",functionLayeredList);
        return resultPage("/manage/role/role_function");
    }

    /**
     * 保存角色授权信息
     * @param roleId 角色ID
     * @param functionIds 权限ID组
     * @return Map<String,Object>
     */
    @RequestMapping("/addSubjectAndFunctionToRole")
    @ResponseBody
    @OpLog(module = AdminModuleEnum.SYS_USER,action = "修改角色授权信息")
    public Map<String,Object> addSubjectAndFunctionToRole(@RequestParam("roleId") BigDecimal roleId ,
                                                          @RequestParam(value = "functionIds",required = false) String functionIds){
        return roleFunctionService.saveRoleFunctionSubject(roleId,functionIds);
    }

    /**
     * 处理角色对专业是否拥有的状态
     * @param roleId 角色的ID
     * @param subjectLayeredList 查询得到的专业列表
     * @return  List<Map<String,Object>>
     */
    private List<Map<String,Object>> handleSubjectHasStatus(BigDecimal roleId,List<Map<String,Object>> subjectLayeredList){
        if(ObjectUtils.isNotEmpty(subjectLayeredList)){
            List<Map<String,Object>> roleSubjectList = roleSubjectService.findRoleSubjectList(roleId);
            if(ObjectUtils.isNotEmpty(roleSubjectList)){
                Map<String,Map<String,Object>> subjectMaps = roleSubjectList.stream().collect(Collectors.toMap(e->e.get("subjectId").toString(),e->e));
                List<Map<String,Object>> _subjectLayeredList = new ArrayList<>();
                for(Map<String,Object> subject : subjectLayeredList){
                    Map<String,Object> roleSubject = subjectMaps.get(subject.get("id").toString());
                    if(roleSubject==null){
                        subject.put("hasSubjectStatus",false);
                    }else{
                        subject.put("hasSubjectStatus",true);
                    }
                    List<Map<String,Object>> childSubjectList = (List<Map<String,Object>>)subject.get("childSubjectList");
                    if(ObjectUtils.isNotEmpty(childSubjectList)){
                        for(Map<String,Object> child : childSubjectList){
                            roleSubject  = subjectMaps.get(child.get("id").toString());
                            if(roleSubject==null){
                                child.put("hasSubjectStatus",false);
                            }else{
                                child.put("hasSubjectStatus",true);
                            }
                        }
                        subject.put("childSubjectList",childSubjectList);
                    }
                    _subjectLayeredList.add(subject);
                }
                return _subjectLayeredList;
            }
        }
        return subjectLayeredList;
    }
    /**
     * 处理角色对对权限的是否拥有的状态
     * @param roleId 角色的ID
     * @param functionLayeredList 查询得到的权限列表
     * @return  List<Map<String,Object>>
     *
     */
    private List<Map<String,Object>> handleFunctionHasStatus(BigDecimal roleId,List<Map<String,Object>> functionLayeredList){
        if(ObjectUtils.isNotEmpty(functionLayeredList)){
            List<Map<String,Object>> roleFunctionList = roleFunctionService.findRoleFunctionList(roleId);
            if(ObjectUtils.isNotEmpty(roleFunctionList)){
                List<Map<String,Object>> _functionLayeredList = new ArrayList<>();
                Map<String,Map<String,Object>> functionMaps = roleFunctionList.stream().collect(Collectors.toMap(e->e.get("functionId").toString(),e->e));
                for(Map<String,Object> function : functionLayeredList){
                    Map<String,Object> roleFunction = functionMaps.get(function.get("id").toString());
                    if(roleFunction==null){
                        function.put("hasFunctionStatus",false);
                    }else{
                        function.put("hasFunctionStatus",true);
                    }
                    List<Map<String,Object>> childFunctionList = (List<Map<String,Object>>)function.get("childSysFunctionList");
                    handleChildFunctionHasStatus(childFunctionList,roleFunction,functionMaps,function);
                    _functionLayeredList.add(function);
                }
                return _functionLayeredList;
            }
        }
        return functionLayeredList;
    }

    /**
     * 设置子节点是否选中
     * @param childFunctionList
     * @param roleFunction
     * @param functionMaps
     * @param function
     */
    private void handleChildFunctionHasStatus(List<Map<String,Object>> childFunctionList,Map<String,Object> roleFunction,Map<String,Map<String,Object>> functionMaps,Map<String,Object> function){
        if(ObjectUtils.isNotEmpty(childFunctionList)){
            for(Map<String,Object> child : childFunctionList){
                roleFunction = functionMaps.get(child.get("id").toString());
                if(roleFunction==null){
                    child.put("hasFunctionStatus",false);
                }else{
                    child.put("hasFunctionStatus",true);
                }
                List<Map<String,Object>> childSysFunctionList = (List<Map<String,Object>>) child.get("childSysFunctionList");
                if(childSysFunctionList !=null){
                    for(Map<String,Object> child_ : childSysFunctionList){
                        roleFunction = functionMaps.get(child_.get("id").toString());
                        if(roleFunction==null){
                            child_.put("hasFunctionStatus",false);
                        }else{
                            child_.put("hasFunctionStatus",true);
                        }
                    }
                }
            }
            function.put("childSysFunctionList",childFunctionList);
        }

    }


    /**
     * 验证用户是否拥有该专业的权限
     * @return
     */
    @RequestMapping("/VerifySubjectFunctionToRole")
    @ResponseBody
    public Map<String,Object> VerifySubjectFunctionToRole (HttpServletRequest request,@RequestParam("subjectId") String subjectId ){
        List<Map<String, Object>> layeredUserFunctionList = subjectService.findSysUserSubjectList(loginUtil.getLoginUserId(request));
        Map<String, Object> subject =null;
        if(ObjectUtils.isNotEmpty(layeredUserFunctionList)){
            Map<String, Object> subjectMap = layeredUserFunctionList.stream().collect(Collectors.toMap(e -> e.get("id").toString(), e -> e));
            subject = (Map<String, Object>)subjectMap.get(subjectId);
            if(!ObjectUtils.isNotEmpty(subject)){
                Iterator<Map.Entry<String, Object>> iterator = subjectMap.entrySet().iterator();
                while(iterator.hasNext()){
                    Map<String, Object> subjectTo= (Map<String, Object>) iterator.next().getValue();
                    List<Map<String, Object>> childSubjectList = (List<Map<String, Object>>) subjectTo.get("childSubjectList");
                    if(ObjectUtils.isNotEmpty(childSubjectList)) {
                        subject = childSubjectList.stream().collect(Collectors.toMap(e -> e.get("id").toString(), e -> e)).get(subjectId);
                    }
                    if(ObjectUtils.isNotEmpty(subject)){
                        return  ResultUtil.SUCCESS("拥有该专业的操作权限");
                    }
                }
            }else{
                return  ResultUtil.SUCCESS("拥有该专业的操作权限");
            }
        }
        return  ResultUtil.ERROR("您的账号没有这个专业的操作权限");
    }

    @RequestMapping("/VerifyEyeUserRoles")
    @ResponseBody
    public Map<String,Object>  VerifyEyeUserRoles(HttpServletRequest request,@RequestParam("roleId") Integer roleId){
        List<Map<String, Object>> userRoleListByUserId = userRoleService.findUserRoleListByUserId(loginUtil.getLoginUserId(request));
        if(!userRoleListByUserId.isEmpty()){
            Map<String, Object> stringObjectMap = userRoleListByUserId.get(0);
            String roleIdTo = stringObjectMap.get("id").toString();
            if(Integer.valueOf(roleIdTo)==roleId){
                return  ResultUtil.ERROR("修改了当前账号角色的权限需要重新登录，才可使用新权限") ;
            }
        }
        return  ResultUtil.SUCCESS("保存成功") ;
    }

}